<?php
require_once "./mysql.php";
$Admin = $_REQUEST["admin"];
$Pass = $_REQUEST["pass"];

function generateToken($length = 32) {
    // 定义可用于生成Token的字符
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    // 创建一个空字符串，用于存放生成的Token
    $token = '';
    // 计算需要生成的Token长度
    $charactersLength = strlen($characters);
    // 使用一个安全的随机数生成器
    for ($i = 0; $i < $length; $i++) {
        // 从字符集随机选择一个字符并添加到Token中
        $token .= $characters[rand(0, $charactersLength - 1)];
    }
    // 返回生成的Token
    return $token;
}

if (!isset($Admin) || !isset($Pass)) {
    exit(json_encode([
        "code" => 0,
        "msg" => "不能留空"
    ],JSON_UNESCAPED_UNICODE));
}

//查询语句
/** @var PDO $pd */
$statement = $pd->query("SELECT * FROM admin WHERE admin = '$Admin' AND pass = md5('$Pass')");
if (!(count($statement->fetchAll()) > 0)){
    exit(json_encode([
        "code" => 0,
        "msg" => "管理员账号密码错误"
    ],JSON_UNESCAPED_UNICODE));
}

//insert create Token
$token = generateToken();
$query = "INSERT INTO token (admin, token) VALUES ('$Admin', '$token')";
$result = $pd->exec($query);
if($result){
    exit(json_encode([
        "code" => 1,
        "msg" => "创建成功",
        "token" => $token
    ],JSON_UNESCAPED_UNICODE));
}
exit(json_encode([
    "code" => 0,
    "msg" => "创建失败"
],JSON_UNESCAPED_UNICODE));
